/**
 * User: Obi
 * Date: 21.08.11
 * Time: 14:06
 */
package com.jediflasher.game_client.view {
	import alternativa.engine3d.core.Camera3D;
	import alternativa.engine3d.core.Object3D;
	import alternativa.engine3d.core.Resource;
	import alternativa.engine3d.core.View;

	import com.jediflasher.game_client.data.BaseData;

	import flash.display.Stage3D;
	import flash.events.Event;

	public class Base3DScene extends BaseView {

		public function Base3DScene(data:BaseData) {
			super(data);
		}

		/**
		 * @private
		 */
		private var _3dInitialized:Boolean = false;

		/**
		 * @private
		 */
		protected var _camera:Camera3D;

		/**
		 * @private
		 */
		protected var _rootContainer:Object3D = new Object3D();

		/**
		 * @private
		 */
		protected var _stage3d:Stage3D;

		/**
		 * @inheritDoc
		 */
		override public function render(event:Event = null):Boolean {
			if(!super.render(event)) return false;

			if(!this._camera) {
				this._camera = new Camera3D(0.1, 10000);
				this._camera.view = new View(stage.stageWidth, stage.stageHeight, false, 0, 0, 4);
			}
			else {
				this._camera.view.width = stage.stageWidth;
				this._camera.view.height =  stage.stageHeight;
			}

			if(!super.contains(this._camera.view)) {
				super.addChild(this._camera.view);
			}

			if(!super.contains(this._camera.diagram)) {
				super.addChild(this._camera.diagram);
			}

			this._camera.rotationX = -120*Math.PI/180;
			this._camera.y = -800;
			this._camera.z = 400;

			if(!this._rootContainer.contains(this._camera)){
				this._rootContainer.addChild(this._camera);
			}

			if(!this._stage3d) {
				this._stage3d = stage.stage3Ds[0];
				this._stage3d.addEventListener(Event.CONTEXT3D_CREATE, this.handler_contextCreate);
				this._stage3d.requestContext3D();
			}

			return this._3dInitialized;
		}

		override public function clear(event:Event = null):void {
			super.clear(event);

			if(this._camera) {
				super.removeChild(this._camera.view);
				super.removeChild(this._camera.diagram);
				this._rootContainer.removeChild(this._camera);
			}

			if(this._stage3d) {
				this._stage3d.removeEventListener(Event.CONTEXT3D_CREATE, this.handler_contextCreate);
				this.stage.removeEventListener(Event.ENTER_FRAME, this.handler_enterFrame);
			}

			this._3dInitialized = false;
		}

		public function add3dChild(child:Object3D):Object3D {
			return this._rootContainer.addChild(child)
		}

		public function remove3dChild(child:Object3D):Object3D {
			return this._rootContainer.removeChild(child);
		}

		/**
		 * @private
		 */
		private function handler_contextCreate(event:Event):void {
			for each (var resource:Resource in this._rootContainer.getResources(true)) {
				resource.upload(this._stage3d.context3D);
			}

			this._3dInitialized = true;
			super.render();
			super.stage.addEventListener(Event.ENTER_FRAME, this.handler_enterFrame);
		}

		/**
		 * @private
		 */
		private function handler_enterFrame(event:Event):void {
			this._camera.render(this._stage3d);
		}
	}
}
